package com.zerox.sbdemo.controller;

import com.zerox.sbdemo.pojo.Fruit;
import com.zerox.sbdemo.service.FruitService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;

@Controller
public class FruitController {

    @Autowired
    private FruitService fruitService;


    @GetMapping("/list")
    public String list(Model model, HttpServletRequest request){
        List<Fruit> list = fruitService.list();
        model.addAttribute("list",list);

        model.addAttribute("date",new Date());
        request.setAttribute("test","request");
        request.getSession().setAttribute("test","session");
        return "list";
    }

    @GetMapping("/fruit/{id}")
    public String view(@PathVariable Integer id,Model model){
        Fruit fruit = fruitService.getById(id);
        model.addAttribute("fruit",fruit);
        return "view";
    }

    @GetMapping("/delete/{id}")
    public String delete(@PathVariable("id")Integer id){
        fruitService.removeById(id);

        return "redirect:/list";
    }

    @GetMapping("toAdd")
    public String toAdd(){
        return "add";
    }

    @PostMapping("/fruit")
    public String add(Fruit fruit){
        fruitService.save(fruit);
        return "redirect:list";
    }

    @GetMapping("/update/{id}")
    public String toUpdate(Model model,@PathVariable("id")Integer id){
        Fruit fruit = fruitService.getById(id);
        model.addAttribute("fruit",fruit);
        return "update";
    }

    @PostMapping("/update")
    public String toUpdate(Fruit fruit){
        fruitService.updateById(fruit);
        return "redirect:list";
    }
}
